#include "mandate.h"
//#include <mysql/mysql.h>
//#include <crypt.h>

//声明
//int rand_salt(char *salt);
//int passwd_check(char *username,char *passwd,MYSQL *mysql ,int *user_id);

//注：  修改mysql_real_connect 中的密码以及 表名称
//      添加头文件
//      链接库文件
int passwd_check(char *username,char *passwd,MYSQL *mysql ,int *user_id){

    char sql_passwd[1024]={0};

    sprintf(sql_passwd,"select * from user_tbl where user_name='%s';",username);
    int qret=mysql_query(mysql,sql_passwd);
    if(qret!=0){
        fprintf(stderr,"SQL statment error :%s\n",mysql_error(mysql));
    }

    MYSQL_RES *res=mysql_store_result(mysql);
    MYSQL_ROW row=mysql_fetch_row(res);

    char salt[13]={0};
    char cryp[256]={0};

    if(row==NULL){//用户不存在 注册
        rand_salt(salt);
        sprintf(cryp,"%s",crypt(passwd,salt));
        sprintf(sql_passwd,"insert into user_tbl (user_name,salt,encrypted_password) value('%s','%s','%s');",username,salt,cryp);
        qret=mysql_query(mysql,sql_passwd);
        if(qret!=0){
            fprintf(stderr,"SQL statment error :%s\n",mysql_error(mysql));
        }
        //获取id并返回
        sprintf(sql_passwd,"select *from user_tbl where user_name = '%s'; ",username);
        qret=mysql_query(mysql,sql_passwd);
        if(qret!=0){
            fprintf(stderr,"SQL seletct error :%s\n",mysql_error(mysql));
        }
        res=mysql_store_result(mysql);
        row=mysql_fetch_row(res);
        *user_id=atoi(row[0]);

        return 1;//注册成功
    }
    //用户已存在 验证密码
    else if(row){
        strcpy(salt,row[2]);
        strcpy(cryp,crypt(passwd,salt));

        if(strcmp(row[3],cryp)==0){//密码正确 获取id
            sprintf(sql_passwd,"select *from user_tbl where user_name = '%s'; ",username);
            qret=mysql_query(mysql,sql_passwd);
            if(qret!=0){
                fprintf(stderr,"SQL seletct error :%s\n",mysql_error(mysql));
            }
            res=mysql_store_result(mysql);
            row=mysql_fetch_row(res);
            *user_id=atoi(row[0]);
            return 0;//密码正确
        }
        else{
            return -1;//密码错误 user_id为-1;
        }
        return -1;
    }
    return -1;
}
int rand_salt(char *salt){
    srand(time(NULL));
    char base_salt[]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789./";
    char head[]="$6$";
    char tail[]="$";

    char mid[9]={0};
    for(int i=0;i<8;i++){
        mid[i]=base_salt[rand()%64];
    }
    sprintf(salt,"%s%s%s",head,mid,tail);

    return 0;
}
